package com.wen.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


/**
 * shell命令执行工具类
 * <p>
 *
 * @author liwen <devinlive@163.com>
 * @version 1.0
 * @since 2022/12/16 21:28
 */
public class ShellCommand {

    private static String cmdString;
    private static String userName;
    private static String passWord;

    private ShellCommand(){
        throw new IllegalStateException("Utility class");
    }
    public ShellCommand (String cmdString, String userName, String passWord) {
        ShellCommand.cmdString = cmdString;
        ShellCommand.userName = userName;
        ShellCommand.passWord = passWord;
    }

    public static void doExec() {
        String str;
        try {
            ProcessBuilder pb = new ProcessBuilder(cmdString, userName, passWord);  //  ProcessBuilder(可执行进程，需要使用的参数)
            Process process = pb.start();                                             // 执行
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));     // 获取进程执行成功后的标准输出流 str
            while ( (str=bufferedReader.readLine()) != null)
            {
                System.out.println(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static String[] getSystemctlCmd(String status, String serviceName) {
        return new String[]{"systemctl",status,serviceName};
    }

    public static class ExecResult {

       public final int exitCode;
       public final String stdout;
       public final String stderr;

        public ExecResult(int exitValue, String stdout, String stderr) {
            this.exitCode = exitValue;
            this.stdout = stdout;
            this.stderr = stderr;

        }
    }


    // execute a command and return
    public static ExecResult exec(String[] cmd) throws IOException, InterruptedException {
        Runtime rt = Runtime.getRuntime();
        Process process = rt.exec(cmd);
        process.getErrorStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
        StringBuilder stdoutBuilder = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            stdoutBuilder.append('\n');
            stdoutBuilder.append(line);
        }
        br = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        StringBuilder stderrBuilder = new StringBuilder();
        while ((line = br.readLine()) != null) {
            stderrBuilder.append('\n');
            stderrBuilder.append(line);
        }
        process.waitFor();
        return new ExecResult(process.exitValue(), stdoutBuilder.toString(), stderrBuilder.toString());
    }


}